package learningThread.syn.synchronizedMethodLockObj.lock.condition.which;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * condition.await();前必须调用 lock.lock()获取对象锁
 * Object中的wait相当于lock中的await
 *           notify相当于condition中的signal
 *           notifyAll相当于condition中的notifyAll
 *
 * condition最期待的时  可通知指定线程
 */
public class MyService {

    private Lock lock = new ReentrantLock();

    private Condition conditionA = lock.newCondition();

    private Condition conditionB = lock.newCondition();

    public void awaitA(){
        try {
            System.out.println("开始进入锁A");
            lock.lock();
            System.out.println("即将释放锁A");
            conditionA.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println("释放锁A完成");
        }
    }

    public void signalA(){
        try {
            lock.lock();
            System.out.println("signal A 时间为:"+System.currentTimeMillis());
            conditionA.signal();
        } finally {
            lock.unlock();
        }

    }

    public void awaitB(){
        try {
            System.out.println("开始进入锁B");
            lock.lock();
            System.out.println("即将释放锁B");
            conditionB.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            System.out.println("释放锁B完成");
        }
    }

    public void signalB(){
        try {
            lock.lock();
            System.out.println("signal B 时间为:"+System.currentTimeMillis());
            conditionB.signal();
        } finally {
            lock.unlock();
        }

    }
}
